//
//  MemberDetailViewController.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/6/1.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit

//枚举
public enum RefreshType : Int {
    
    case None   //无
    case PullRefresh  //下拉刷新
    case PushRefresh //上拉加载更多
}

class MemberDetailViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,HeaderFooterViewDelegate{

    
    
    
    @IBOutlet weak var memberDetailTableView: UITableView!
    
    var memberOrHistoryIsOne:Bool?
    var url:String?
    var paramDic:[String:String] = [String:String]()
    
    var memberHeadView:MemberHeaderView?
    var memberSource:[String:String]?//字典类型的用于MCVC传值过来~~传值
    var paramDictionary = [String:AnyObject]?()//用于网络请求数据
    var pageIndex:Int = 1
    var pageSize:Int = 20
    var orderDataSource:[[String:AnyObject]] = [[String:AnyObject]]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if memberOrHistoryIsOne == true{
            self.initUserface()
            self.RegistrationSectionHeaderView()
            self.loadData(RefreshType.None)
            self.addPullPushRefresh()
        }
        
        if memberOrHistoryIsOne == false{
            self.RegistrationSectionHeaderView()
            self.loadData(RefreshType.None)
            self.addPullPushRefresh()
        }
       
        

    }
    
    

    //头部视图部分
    func initUserface(){
       //加载XIB对象MemberHeaderView
        let view = NSBundle.mainBundle().loadNibNamed("MemberHeaderView", owner: nil, options: nil).first as! MemberHeaderView  //虽然是数组但是只有一个元素，所以可以取第一个.要创建一个属性去记录它
        self.memberHeadView = view
        view.frame = CGRectMake(0, 0, ScreenWidth*0.96,275)

        view.nikeNameLabel.text = memberSource!["vip_nickname"]
        view.phoneLabel.text = memberSource!["vip_mobile"]
        view.vipTypeLabel.text = memberSource!["sigd_discount"]
        view.accountLabel.text  = memberSource!["uvgrade_money"]
        view.consumeLabel.text = memberSource!["uvgrade_consume_money"]

        let superview = UIView(frame: CGRectMake(0,0,ScreenWidth*0.96,275))
        superview.addSubview(view)

        //设置tableView headerView
        self.memberDetailTableView.tableHeaderView = superview
        
       
    }

    //注册Section HeaderView
    func RegistrationSectionHeaderView(){
        
        self.memberDetailTableView.registerClass(MemberHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "MemberHeaderFooterView")
        self.memberDetailTableView.registerClass(MemberDetialCell.self, forCellReuseIdentifier: "MemberDetialCell")

    }
    
    
    
    func addPullPushRefresh(){
        
        //下拉刷新
        self.memberDetailTableView.addPullRefreshHandler { [weak self] in
            //获取第一页数据
            self?.pageIndex = 1
            self?.loadData(RefreshType.PullRefresh)
            
        }
        //上拉加载
        self.memberDetailTableView.addPushRefreshHandler { [weak self] in
            //获取下一页数据
            self?.pageIndex += 1
            self?.loadData(RefreshType.PushRefresh)
        }
        
    }
    

    //MARK:--loadData 网络请求
    /**
    1.楼上有枚举
    
    2.
    body:{
    "shop_id": "11",//店铺ID（单店）
    "vip_id": "0",//会员ID
    "limit": "0,10",//	从第一条开始，取10条记录（10表示页大小）
    }
    
    */
    func loadData(type:RefreshType){ //ReflectType
        
        let maxCount = self.pageIndex * self.pageSize
        let location = maxCount - self.pageSize
        let limitStr = "\(location),\(self.pageSize)"
        //let limitStr = "0,20"
        paramDic.updateValue(limitStr, forKey: "limit")
        
        print("+++__+_+_)+)+)+",paramDic,url)
    
        //网络请求//paramDics:接口需要的数据
        NetTool .requestX("加载中", urlString: url!, paramDictionary: ["body":paramDic], successAction: { (responseObject) -> Void in
            MBProgressHUD.showSuccess("加载成功")
            MBProgressHUD.hideHUD()
            print("=====")
            print(responseObject)
            print("=====")
            if type == .PullRefresh{
                //下拉刷新
                self.orderDataSource.removeAll()
                
            }
            
            
            //在数组中加新数据
//            self.orderDataSource.appendContentsOf(responseObject["body"] as! [[String:AnyObject]])
            self.addNewData(responseObject["body" ] as! [[String:AnyObject]])
            //加载数据
            self.memberDetailTableView.reloadData()
            //停止刷新
            self.stopPullPushRefresh(type)
            
//
            }) { (error) -> Void in
                
                
        }
    }
    
    
    func addNewData(newData:[[String:AnyObject]]) {
    
        
        //例如：goods~~~~[{type:"小菜"，“name”:"白菜"} ，{type:"小菜"，“name”:"番茄"}，{type:"水果"，“name”:"苹果"}]
        //遍历得到两个数组
        //typeStore:(类型数组)["小菜","水果"]
        //goodByType:(对应类型的数组)[[小菜类型的食物],[水果类型的食物]]
        //当typeStore中增加元素时，goodByType新增一个对应的数组
        
        
        //遍历每个订单
        for var order in newData{
            
            //
            let goods = order["goods"] as! [[String:AnyObject]]//传过来的菜
            var typeStore = [String]()//存储类型的数组
            var goodByType = [[[String:AnyObject]]]()//存储对应类型的食物 的数组
            
            //遍历食物列表进行分类
            for singleGood in goods{
                
                let type = singleGood["kindName"] as! String//singleGood某样具体的食物名字
                if !typeStore.contains(type){//如果不包含则添加到typeStore，并且给goodByType中添加数组保存对应类型数据
                    
                    typeStore.append(type)
                    goodByType.append([])//[]指添加空数组
                }
                
                let index = typeStore.indexOf(type)//根据type取到typeStore中该type的下标
                var singleGoodStore = goodByType[index!] //根据下标 在goodByType对应下标存对应类型的 食物存放数组
                singleGoodStore.append(singleGood)//添加食物
                goodByType.replaceRange(Range(start: index!, end: index!+1), with: [singleGoodStore])//替换成最新的 食物存放数组
                
            }
            
            
            //食物列表处理完毕 更新
            order.updateValue(goodByType, forKey: "goods")
            order.updateValue(typeStore, forKey: "types")
            
            order .updateValue(NSNumber(bool: false), forKey: "selected")//默认section中cell收起
            //数据源添加
            self.orderDataSource.append(order)
        }
        
    }

    
    func stopPullPushRefresh(type:RefreshType){
        
        if type == .PullRefresh{
            self.memberDetailTableView.stopPullRefreshEver()
            
        }else if type == .PushRefresh{
            self.memberDetailTableView.stopPushRefreshEver()
            
        }
    }

    
    //UITableView的协议与代理~
    
    //每个订单都是一个Section，订单里面的食物列表是cell，
    //点击headerView（订单时）展开cell（食物）或者收起cell（食物）
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return orderDataSource.count
    }
    
    //cell个数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        return 0//先默认返回0
        
        //取到订单
        let order = self.orderDataSource[section]//整个订单列表用下标取取到对应cell的订单
        let typeStore = order["types"] as? [String]
        
        //取到表示
        let selectedNumber = order["selected"] as! NSNumber
        if selectedNumber.boolValue{
            //展开 返回全部cell个数
            return typeStore!.count
        }else{
            //关闭
            return 0//返回0
        }

    }
    
    
    //HeaderView 高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 180
    }
    
    //cell高度
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        return 0//先默认返回0
        let order = self.orderDataSource[indexPath.section]//整个订单列表用下标取取到对应的
        let goodByType = order["goods"] as! [[[String:AnyObject]]]
        let cellGoods = goodByType[indexPath.row]
        
        var height = 0
        if indexPath.row == 0{
            //显示详情消费记录的label
            height += 35
        }
        
        //每个食物的高度
        height += (cellGoods.count - 1) * 2
        //每个食物的高度 * 个数
        height += cellGoods.count * 60
        //cell结束时要空一点
        height += 10
        
        
        return CGFloat(height)

        
    }
    
    //返回HeaderView ~~ 和cell一样有重用，和cell使用方法类似
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("MemberHeaderFooterView") as! MemberHeaderFooterView
        
        //显示数据
        headerView.orderDataource = self.orderDataSource[section]
        
        //设置代理HeaderFooterViewDelegate
        headerView.delegate = self
        headerView.section = section
        return headerView
    }
    
    
    //MARK --   HeaderFooterViewDelegate
    //实现对应的代理方法HeaderFooterViewDelegate
    func didSelect(headerFooterView: MemberHeaderFooterView) {
        //HeaderView 的selected状态已修改
        //根据此状态判断section是展开还是收起
        //tableview 刷新对应section的数据
        //根据headerview得到对应的section
        let section = headerFooterView.section
        
        var order = self.orderDataSource[section]//每个cell的收起与展开
        let selectedNumber = order["selected"] as! NSNumber
        if selectedNumber.boolValue{
            //当前展开则要收起
            order.updateValue(NSNumber(bool: false), forKey: "selected")
            
        }else
        {
            //当前收起，则要展开
            order.updateValue(NSNumber(bool: true), forKey: "selected")
        }
        //替换
        self.orderDataSource.replaceRange(Range(start: section, end: section+1), with: [order])//with好像是被替换的内容
        //加载数据
        //刷新
        self.memberDetailTableView.reloadSections(NSIndexSet(index: section), withRowAnimation: UITableViewRowAnimation.None)
        
    }

    //返回cell
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell  = tableView.dequeueReusableCellWithIdentifier("MemberDetialCell", forIndexPath: indexPath) as! MemberDetialCell
        
        //食物存放数组
        let order = self.orderDataSource[indexPath.section]
        let goodByType = order["goods"] as! [[[String:AnyObject]]]
        let cellGoods = goodByType[indexPath.row]
        
        //类型数组
        let typeStore = order["types"] as! [String]
        let cellType = typeStore[indexPath.row]
        
        cell.index = indexPath.row
        cell.foodDatasource = cellGoods
        cell.classifyLabel.text = cellType
        return cell
    }

}
